package service

import (
	"sort"
	"shop/config/constant"
	"shop/dao"
	"shop/entity"
)

// GetGoodsMenuList 返回在售的商品菜单列表
func GetGoodsMenuList(shopId int) []*entity.GoodsCategory {
	goodsList := make([]*entity.Goods, 0, 0)
	dao.GetDB().Table(entity.TableNameGoods).Where("shop_id=? and status=?", shopId, constant.GoodsStatusOnSell).Find(&goodsList)

	// 菜单分类, 关联类别和商品
	categoryList := make([]*entity.GoodsCategory, 0, 0)
	dao.GetDB().Table(entity.TableNameGoodsCategory).Where("shop_id=? and show_status=true", shopId).Find(&categoryList)
	for _, category := range categoryList {
		category.GoodsList = make([]*entity.Goods, 0, 0)
		for _, goods := range goodsList {
			if goods.GoodsCategoryId == category.Id {
				goods.GoodsCategoryName = category.Name
				goods.ParsePropertyList() // 反序列化属性列表
				category.GoodsList = append(category.GoodsList, goods)
			}
		}
		sort.Slice(category.GoodsList, func(a, b int) bool { return category.GoodsList[b].DisplayOrder > category.GoodsList[a].DisplayOrder })
	}

	sort.Slice(categoryList, func(a, b int) bool { return categoryList[b].DisplayOrder > categoryList[a].DisplayOrder })
	return categoryList
}

func GetGoodsById(goodsId int64) *entity.Goods {
	goods := entity.Goods{}
	dao.GetDB().Model(&goods).Where("id", goodsId).Take(&goods)
	goods.ParsePropertyList()
	return &goods
}
